package com.soFun.service;

import dev.langchain4j.chain.ConversationalChain;
import dev.langchain4j.memory.ChatMemory;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.chat.ChatLanguageModel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * AI链服务，展示LangChain4j的链式处理能力
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class AiChainService {

    private final ChatLanguageModel chatLanguageModel;
    
    // 存储用户会话
    private final Map<String, ConversationalChain> conversations = new ConcurrentHashMap<>();
    
    /**
     * 创建新的会话
     * @return 会话ID
     */
    public String createConversation() {
        String conversationId = UUID.randomUUID().toString();
        log.info("创建新会话，ID: {}", conversationId);
        
        try {
            // 使用兼容的API为beta2版本创建记忆窗口
            ChatMemory chatMemory = MessageWindowChatMemory.builder()
                    .maxMessages(10)
                    .build();
            
            // 创建对话链
            ConversationalChain chain = ConversationalChain.builder()
                    .chatLanguageModel(chatLanguageModel)
                    .chatMemory(chatMemory)
                    .build();
            
            conversations.put(conversationId, chain);
            log.info("会话创建成功: {}", conversationId);
            return conversationId;
        } catch (Exception e) {
            log.error("创建会话失败: {}", e.getMessage(), e);
            throw new RuntimeException("创建会话失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 在会话中发送消息
     * @param conversationId 会话ID
     * @param message 用户消息
     * @return AI回复
     */
    public String sendMessage(String conversationId, String message) {
        log.info("向会话 {} 发送消息: {}", conversationId, message);
        ConversationalChain chain = conversations.get(conversationId);
        if (chain == null) {
            log.warn("会话不存在: {}", conversationId);
            throw new IllegalArgumentException("会话不存在，ID: " + conversationId);
        }
        
        try {
            // 执行对话链
            String response = chain.execute(message);
            log.info("会话 {} 响应完成，响应长度: {}", conversationId, response.length());
            return response;
        } catch (Exception e) {
            log.error("处理会话消息失败: {}", e.getMessage(), e);
            throw new RuntimeException("处理会话消息失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 获取会话状态信息
     * @param conversationId 会话ID
     * @return 会话状态信息
     */
    public Map<String, Object> getConversationInfo(String conversationId) {
        log.info("获取会话信息: {}", conversationId);
        if (!conversations.containsKey(conversationId)) {
            log.warn("会话不存在: {}", conversationId);
            throw new IllegalArgumentException("会话不存在，ID: " + conversationId);
        }
        
        Map<String, Object> info = new HashMap<>();
        info.put("conversationId", conversationId);
        info.put("active", true);
        info.put("createdAt", System.currentTimeMillis());
        return info;
    }
    
    /**
     * 删除会话
     * @param conversationId 会话ID
     */
    public void deleteConversation(String conversationId) {
        log.info("删除会话: {}", conversationId);
        conversations.remove(conversationId);
    }
} 